//
//  StickyHeadersLayout.swift
//  CustomizeCollectionView
//
//  Created by GZOffice_hao on 2019/4/28.
//  Copyright © 2019 VT. All rights reserved.
//

import UIKit

class StickyHeadersLayout: UICollectionViewFlowLayout {
    
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        guard let collectionView = collectionView, var layoutAttributes = super.layoutAttributesForElements(in: rect) else {
            return nil
        }
        
        let headerNeedingLayout = NSMutableIndexSet()
        for attributes in layoutAttributes {
            if attributes.representedElementCategory == .cell {
                headerNeedingLayout.add(attributes.indexPath.section)
            }
        }
        for attributes in layoutAttributes {
            if let kind = attributes.representedElementKind, kind == UICollectionView.elementKindSectionHeader {
                headerNeedingLayout.remove(attributes.indexPath.section)
            }
        }
        print(headerNeedingLayout)
        headerNeedingLayout.forEach { index in
            let indexPath = IndexPath(item: 0, section: index)
            if let attributes = layoutAttributesForSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, at: indexPath) {
                layoutAttributes.append(attributes)
            }
        }
        
        for attributes in layoutAttributes {
            if let elementKind = attributes.representedElementKind, elementKind == UICollectionView.elementKindSectionHeader {
                let section = attributes.indexPath.section
                let attributesForFirstItemInSection = layoutAttributesForItem(at: IndexPath(item: 0, section: section))!
                let attributesForLastItemInSection = layoutAttributesForItem(at: IndexPath(item: collectionView.numberOfItems(inSection: section) - 1, section: section))!
                var frame = attributes.frame
                let offset = collectionView.contentOffset.y
                
                let minY = attributesForFirstItemInSection.frame.minY - frame.height
                let maxY = attributesForLastItemInSection.frame.maxX - frame.height
                
                let y = min(max(offset, minY), maxY)
                frame.origin.y = y
                attributes.frame = frame
                attributes.zIndex = 99
            }
        }
        
        return layoutAttributes
    }
    
    override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
        return true
    }
}
